<template>
  <div class="weight-bearing">
    <div class="page-header">
      <h2>负重线计算</h2>
      <p>计算术前负重线(WBL)和规划目标WBL</p>
    </div>

    <div class="content-wrapper">
      <!-- 左侧计算工具 -->
      <div class="calculation-panel">
        <el-card class="tool-card">
          <template #header>
            <div class="card-header">
              <span>WBL计算</span>
            </div>
          </template>

          <div class="wbl-calculation">
            <div class="calculation-method">
              <h4>计算方法</h4>
              <el-radio-group v-model="calculationMethod" class="method-group">
                <el-radio value="automatic">自动计算</el-radio>
                <el-radio value="manual">手动标记</el-radio>
              </el-radio-group>
            </div>

            <div class="landmark-points" v-if="calculationMethod === 'manual'">
              <h4>解剖标记点</h4>
              <div class="points-list">
                <div class="point-item">
                  <el-button
                    size="small"
                    :type="selectedPoint === 'hip' ? 'primary' : ''"
                    @click="selectPoint('hip')"
                  >
                    <el-icon><Aim /></el-icon>
                    髋关节中心
                  </el-button>
                  <span v-if="landmarks.hip" class="point-coords">
                    ({{ landmarks.hip.x }}, {{ landmarks.hip.y }})
                  </span>
                </div>

                <div class="point-item">
                  <el-button
                    size="small"
                    :type="selectedPoint === 'ankle' ? 'primary' : ''"
                    @click="selectPoint('ankle')"
                  >
                    <el-icon><Aim /></el-icon>
                    踝关节中心
                  </el-button>
                  <span v-if="landmarks.ankle" class="point-coords">
                    ({{ landmarks.ankle.x }}, {{ landmarks.ankle.y }})
                  </span>
                </div>

                <div class="point-item">
                  <el-button
                    size="small"
                    :type="selectedPoint === 'knee_medial' ? 'primary' : ''"
                    @click="selectPoint('knee_medial')"
                  >
                    <el-icon><Aim /></el-icon>
                    膝关节内侧
                  </el-button>
                  <span v-if="landmarks.knee_medial" class="point-coords">
                    ({{ landmarks.knee_medial.x }}, {{ landmarks.knee_medial.y }})
                  </span>
                </div>

                <div class="point-item">
                  <el-button
                    size="small"
                    :type="selectedPoint === 'knee_lateral' ? 'primary' : ''"
                    @click="selectPoint('knee_lateral')"
                  >
                    <el-icon><Aim /></el-icon>
                    膝关节外侧
                  </el-button>
                  <span v-if="landmarks.knee_lateral" class="point-coords">
                    ({{ landmarks.knee_lateral.x }}, {{ landmarks.knee_lateral.y }})
                  </span>
                </div>
              </div>

              <div class="point-actions">
                <el-button size="small" @click="clearPoints">
                  <el-icon><Delete /></el-icon>
                  清除标记
                </el-button>
                <el-button size="small" type="primary" @click="calculateWBL" :disabled="!canCalculate">
                  <el-icon><Operation /></el-icon>
                  计算WBL
                </el-button>
              </div>
            </div>

            <div class="auto-calculate" v-else>
              <p class="tip">系统将自动识别解剖标记点并计算负重线</p>
              <el-button type="primary" block @click="autoCalculateWBL">
                <el-icon><MagicStick /></el-icon>
                开始自动计算
              </el-button>
            </div>
          </div>
        </el-card>

        <el-card class="tool-card">
          <template #header>
            <div class="card-header">
              <span>WBL结果</span>
            </div>
          </template>

          <div class="wbl-results">
            <div v-if="!wblData.calculated" class="no-results">
              <el-icon><DataLine /></el-icon>
              <p>请先完成WBL计算</p>
            </div>

            <div v-else class="results-data">
              <div class="result-item">
                <label>术前WBL比例</label>
                <div class="result-value">
                  {{ wblData.preoperative }}%
                  <el-tag :type="getWBLStatus(wblData.preoperative)" size="small">
                    {{ getWBLLabel(wblData.preoperative) }}
                  </el-tag>
                </div>
              </div>

              <div class="result-item">
                <label>WBL偏移距离</label>
                <div class="result-value">{{ wblData.offset }}mm</div>
              </div>

              <div class="result-item">
                <label>膝关节宽度</label>
                <div class="result-value">{{ wblData.kneeWidth }}mm</div>
              </div>

              <el-divider />

              <div class="target-planning">
                <h4>目标WBL规划</h4>
                <div class="target-input">
                  <label>目标WBL比例</label>
                  <el-input-number
                    v-model="targetWBL"
                    :min="0"
                    :max="100"
                    :step="1"
                    size="small"
                  />
                  <span>%</span>
                </div>

                <div class="target-result">
                  <div class="target-item">
                    <label>需要调整距离</label>
                    <span class="adjust-distance">{{ calculateAdjustment() }}mm</span>
                  </div>
                  <div class="target-item">
                    <label>调整方向</label>
                    <span class="adjust-direction">{{ getAdjustmentDirection() }}</span>
                  </div>
                </div>

                <el-button type="primary" size="small" block @click="applyTargetWBL">
                  应用目标WBL
                </el-button>
              </div>
            </div>
          </div>
        </el-card>

        <el-card class="tool-card">
          <template #header>
            <div class="card-header">
              <span>参考标准</span>
            </div>
          </template>

          <div class="reference-standards">
            <div class="standard-item">
              <label>正常WBL</label>
              <span>50% ± 5%</span>
            </div>
            <div class="standard-item">
              <label>内翻WBL</label>
              <span>< 45%</span>
            </div>
            <div class="standard-item">
              <label>外翻WBL</label>
              <span>> 55%</span>
            </div>
            <div class="standard-item">
              <label>HTO目标</label>
              <span>60-65%</span>
            </div>
            <div class="standard-item">
              <label>DFO目标</label>
              <span>45-50%</span>
            </div>
          </div>
        </el-card>
      </div>

      <!-- 右侧可视化区域 -->
      <div class="visualization-area">
        <el-card class="visualization-card">
          <template #header>
            <div class="visualization-header">
              <span>WBL可视化</span>
              <div class="visualization-controls">
                <el-button-group size="small">
                  <el-button @click="toggleWBLLine">
                    {{ showWBL ? '隐藏' : '显示' }}WBL
                  </el-button>
                  <el-button @click="toggleTargetLine">
                    {{ showTarget ? '隐藏' : '显示' }}目标线
                  </el-button>
                  <el-button @click="toggleMeasurements">
                    {{ showMeasurements ? '隐藏' : '显示' }}测量
                  </el-button>
                </el-button-group>

                <el-button-group size="small">
                  <el-button @click="exportResults">
                    <el-icon><Download /></el-icon>
                    导出
                  </el-button>
                  <el-button @click="printResults">
                    <el-icon><Printer /></el-icon>
                    打印
                  </el-button>
                </el-button-group>
              </div>
            </div>
          </template>

          <div class="canvas-container" ref="canvasContainer">
            <canvas
              ref="wblCanvas"
              class="wbl-canvas"
              @mousedown="handleCanvasClick"
              @mousemove="updateMousePosition"
            ></canvas>

            <div v-if="!imageLoaded" class="canvas-placeholder">
              <el-icon class="placeholder-icon"><Picture /></el-icon>
              <p>请先在影像分析模块加载X光图像</p>
              <el-button type="primary" @click="goToImageAnalysis">
                <el-icon><Right /></el-icon>
                前往影像分析
              </el-button>
            </div>

            <!-- 计算状态提示 -->
            <div v-if="calculating" class="calculating-overlay">
              <el-icon class="is-loading"><Loading /></el-icon>
              <span>正在计算WBL...</span>
            </div>

            <!-- 标记点提示 -->
            <div v-if="selectedPoint && calculationMethod === 'manual'" class="point-tip">
              <div class="tip-content">
                <el-icon><Aim /></el-icon>
                <span>点击图像标记{{ getPointLabel(selectedPoint) }}</span>
              </div>
            </div>
          </div>

          <div class="canvas-status">
            <span>坐标: ({{ mouseX }}, {{ mouseY }})</span>
            <span v-if="wblData.calculated">WBL: {{ wblData.preoperative }}%</span>
            <span v-if="targetWBL">目标: {{ targetWBL }}%</span>
          </div>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, nextTick } from 'vue'
import { useStore } from '../../store'
import {
  Aim,
  Delete,
  Operation,
  MagicStick,
  DataLine,
  Download,
  Printer,
  Picture,
  Right,
  Loading
} from '@element-plus/icons-vue'

// 全局状态
const store = useStore()

// 响应式数据
const calculationMethod = ref('automatic')
const selectedPoint = ref('')
const landmarks = ref({
  hip: null,
  ankle: null,
  knee_medial: null,
  knee_lateral: null
})

const wblData = ref({
  calculated: false,
  preoperative: 0,
  offset: 0,
  kneeWidth: 0
})

const targetWBL = ref(62)
const showWBL = ref(true)
const showTarget = ref(true)
const showMeasurements = ref(true)
const calculating = ref(false)
const mouseX = ref(0)
const mouseY = ref(0)

// 计算属性 - 检查全局图像状态
const imageLoaded = computed(() => store.getters.isImageLoaded())

// DOM引用
const canvasContainer = ref(null)
const wblCanvas = ref(null)

// 计算属性
const canCalculate = computed(() => {
  if (calculationMethod.value === 'automatic') return true
  return landmarks.value.hip && landmarks.value.ankle &&
         landmarks.value.knee_medial && landmarks.value.knee_lateral
})

// 标记点选择
const selectPoint = (point) => {
  selectedPoint.value = point
}

const handleCanvasClick = (event) => {
  if (calculationMethod.value === 'manual' && selectedPoint.value) {
    const rect = wblCanvas.value.getBoundingClientRect()
    const x = Math.round(event.clientX - rect.left)
    const y = Math.round(event.clientY - rect.top)

    landmarks.value[selectedPoint.value] = { x, y }
    selectedPoint.value = ''

    // 重绘画布
    drawCanvas()
  }
}

const updateMousePosition = (event) => {
  const rect = wblCanvas.value.getBoundingClientRect()
  mouseX.value = Math.round(event.clientX - rect.left)
  mouseY.value = Math.round(event.clientY - rect.top)
}

const clearPoints = () => {
  landmarks.value = {
    hip: null,
    ankle: null,
    knee_medial: null,
    knee_lateral: null
  }
  selectedPoint.value = ''
  drawCanvas()
}

// WBL计算
const calculateWBL = () => {
  if (!canCalculate.value) return

  calculating.value = true

  // 模拟计算过程
  setTimeout(() => {
    const hip = landmarks.value.hip
    const ankle = landmarks.value.ankle
    const kneeMedial = landmarks.value.knee_medial
    const kneeLateral = landmarks.value.knee_lateral

    // 计算膝关节中心
    const kneeCenter = {
      x: (kneeMedial.x + kneeLateral.x) / 2,
      y: (kneeMedial.y + kneeLateral.y) / 2
    }

    // 计算膝关节宽度
    const kneeWidth = Math.abs(kneeLateral.x - kneeMedial.x)

    // 计算WBL线与膝关节的交点
    const wblIntersection = calculateWBLIntersection(hip, ankle, kneeMedial, kneeLateral)

    // 计算WBL比例
    const wblPercentage = ((wblIntersection.x - kneeMedial.x) / kneeWidth) * 100

    // 计算偏移距离
    const offset = wblIntersection.x - kneeCenter.x

    wblData.value = {
      calculated: true,
      preoperative: Math.round(wblPercentage * 10) / 10,
      offset: Math.round(offset * 10) / 10,
      kneeWidth: Math.round(kneeWidth * 10) / 10
    }

    calculating.value = false
    drawCanvas()
  }, 2000)
}

const autoCalculateWBL = () => {
  calculating.value = true

  // 模拟自动识别和计算
  setTimeout(() => {
    // 自动设置示例标记点
    landmarks.value = {
      hip: { x: 400, y: 100 },
      ankle: { x: 420, y: 500 },
      knee_medial: { x: 360, y: 300 },
      knee_lateral: { x: 440, y: 300 }
    }

    calculateWBL()
  }, 3000)
}

const calculateWBLIntersection = (hip, ankle, kneeMedial, kneeLateral) => {
  // 计算WBL线与膝关节水平线的交点
  const wblSlope = (ankle.y - hip.y) / (ankle.x - hip.x)
  const wblIntercept = hip.y - wblSlope * hip.x

  const kneeY = kneeMedial.y // 假设内外侧在同一水平线
  const intersectionX = (kneeY - wblIntercept) / wblSlope

  return { x: intersectionX, y: kneeY }
}

// WBL状态判断
const getWBLStatus = (percentage) => {
  if (percentage < 45) return 'danger'
  if (percentage > 55) return 'warning'
  return 'success'
}

const getWBLLabel = (percentage) => {
  if (percentage < 45) return '内翻'
  if (percentage > 55) return '外翻'
  return '正常'
}

// 目标WBL计算
const calculateAdjustment = () => {
  if (!wblData.value.calculated) return 0

  const currentPercentage = wblData.value.preoperative
  const targetPercentage = targetWBL.value
  const kneeWidth = wblData.value.kneeWidth

  const adjustmentPercentage = targetPercentage - currentPercentage
  const adjustmentDistance = (adjustmentPercentage / 100) * kneeWidth

  return Math.round(adjustmentDistance * 10) / 10
}

const getAdjustmentDirection = () => {
  const adjustment = calculateAdjustment()
  if (adjustment > 0) return '向外侧'
  if (adjustment < 0) return '向内侧'
  return '无需调整'
}

const applyTargetWBL = () => {
  console.log('应用目标WBL设置')
  drawCanvas()
}

// 显示控制
const toggleWBLLine = () => {
  showWBL.value = !showWBL.value
  drawCanvas()
}

const toggleTargetLine = () => {
  showTarget.value = !showTarget.value
  drawCanvas()
}

const toggleMeasurements = () => {
  showMeasurements.value = !showMeasurements.value
  drawCanvas()
}

// 辅助函数
const getPointLabel = (point) => {
  const labels = {
    hip: '髋关节中心',
    ankle: '踝关节中心',
    knee_medial: '膝关节内侧',
    knee_lateral: '膝关节外侧'
  }
  return labels[point] || ''
}

const goToImageAnalysis = () => {
  console.log('跳转到影像分析模块')
}

const exportResults = () => {
  console.log('导出WBL计算结果')
}

const printResults = () => {
  console.log('打印WBL报告')
}

// 画布绘制
const drawCanvas = () => {
  const canvas = wblCanvas.value
  if (!canvas) return

  const ctx = canvas.getContext('2d')
  ctx.clearRect(0, 0, canvas.width, canvas.height)

  // 绘制背景
  ctx.fillStyle = '#f8f9fa'
  ctx.fillRect(0, 0, canvas.width, canvas.height)

  // 绘制标记点
  Object.entries(landmarks.value).forEach(([key, point]) => {
    if (point) {
      ctx.fillStyle = '#1890ff'
      ctx.beginPath()
      ctx.arc(point.x, point.y, 6, 0, 2 * Math.PI)
      ctx.fill()

      // 绘制标签
      ctx.fillStyle = '#262626'
      ctx.font = '12px Arial'
      ctx.fillText(getPointLabel(key), point.x + 10, point.y - 10)
    }
  })

  // 绘制WBL线
  if (showWBL.value && landmarks.value.hip && landmarks.value.ankle) {
    ctx.strokeStyle = '#ff4d4f'
    ctx.lineWidth = 2
    ctx.beginPath()
    ctx.moveTo(landmarks.value.hip.x, landmarks.value.hip.y)
    ctx.lineTo(landmarks.value.ankle.x, landmarks.value.ankle.y)
    ctx.stroke()
  }

  // 绘制膝关节线
  if (landmarks.value.knee_medial && landmarks.value.knee_lateral) {
    ctx.strokeStyle = '#52c41a'
    ctx.lineWidth = 2
    ctx.beginPath()
    ctx.moveTo(landmarks.value.knee_medial.x, landmarks.value.knee_medial.y)
    ctx.lineTo(landmarks.value.knee_lateral.x, landmarks.value.knee_lateral.y)
    ctx.stroke()
  }

  // 绘制目标线
  if (showTarget.value && wblData.value.calculated) {
    // 绘制目标WBL位置
    const kneeMedial = landmarks.value.knee_medial
    const kneeLateral = landmarks.value.knee_lateral
    if (kneeMedial && kneeLateral) {
      const kneeWidth = kneeLateral.x - kneeMedial.x
      const targetX = kneeMedial.x + (targetWBL.value / 100) * kneeWidth

      ctx.strokeStyle = '#faad14'
      ctx.lineWidth = 2
      ctx.setLineDash([5, 5])
      ctx.beginPath()
      ctx.moveTo(targetX, kneeMedial.y - 20)
      ctx.lineTo(targetX, kneeMedial.y + 20)
      ctx.stroke()
      ctx.setLineDash([])
    }
  }
}

onMounted(() => {
  nextTick(() => {
    if (wblCanvas.value) {
      const canvas = wblCanvas.value
      canvas.width = 800
      canvas.height = 600
      drawCanvas()
    }
  })
})
</script>

<style scoped>
/* 复用之前的样式结构 */
.weight-bearing {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.page-header {
  margin-bottom: 24px;
}

.page-header h2 {
  margin: 0 0 8px 0;
  color: #262626;
  font-size: 24px;
  font-weight: 500;
}

.page-header p {
  margin: 0;
  color: #8c8c8c;
  font-size: 14px;
}

.content-wrapper {
  flex: 1;
  display: flex;
  gap: 24px;
  min-height: 0;
}

.calculation-panel {
  width: 320px;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.tool-card {
  flex-shrink: 0;
}

.card-header {
  font-weight: 500;
  color: #262626;
}

.wbl-calculation {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.calculation-method h4 {
  margin: 0 0 12px 0;
  font-size: 14px;
  color: #595959;
  font-weight: 500;
}

.method-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.landmark-points h4,
.target-planning h4 {
  margin: 0 0 12px 0;
  font-size: 14px;
  color: #595959;
  font-weight: 500;
}

.points-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
  margin-bottom: 16px;
}

.point-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 8px;
}

.point-coords {
  font-size: 12px;
  color: #8c8c8c;
  font-family: monospace;
}

.point-actions {
  display: flex;
  gap: 8px;
}

.auto-calculate .tip {
  margin: 0 0 16px 0;
  padding: 12px;
  background: #f0f9ff;
  border: 1px solid #d4edda;
  border-radius: 4px;
  font-size: 14px;
  color: #595959;
}

.wbl-results {
  max-height: 400px;
  overflow-y: auto;
}

.no-results {
  text-align: center;
  padding: 40px 0;
  color: #8c8c8c;
}

.no-results .el-icon {
  font-size: 32px;
  margin-bottom: 12px;
}

.results-data {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.result-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.result-item label {
  font-size: 14px;
  color: #595959;
  font-weight: 500;
}

.result-value {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: 600;
  color: #262626;
}

.target-input {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 12px;
}

.target-input label {
  font-size: 14px;
  color: #595959;
  min-width: 80px;
}

.target-result {
  display: flex;
  flex-direction: column;
  gap: 8px;
  margin-bottom: 16px;
}

.target-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.target-item label {
  font-size: 14px;
  color: #595959;
}

.adjust-distance {
  font-weight: 600;
  color: #1890ff;
}

.adjust-direction {
  font-weight: 500;
  color: #262626;
}

.reference-standards {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.standard-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 12px;
  background: #f8f9fa;
  border-radius: 4px;
}

.standard-item label {
  font-size: 14px;
  color: #595959;
}

.standard-item span {
  font-weight: 500;
  color: #262626;
}

.visualization-area {
  flex: 1;
  min-width: 0;
}

.visualization-card {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.visualization-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.visualization-controls {
  display: flex;
  gap: 12px;
}

.canvas-container {
  flex: 1;
  position: relative;
  background: #f8f9fa;
  border: 1px solid #e8e8e8;
  border-radius: 6px;
  overflow: hidden;
  min-height: 400px;
}

.wbl-canvas {
  width: 100%;
  height: 100%;
  cursor: crosshair;
}

.canvas-placeholder {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  text-align: center;
  color: #8c8c8c;
}

.placeholder-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

.calculating-overlay {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 16px 24px;
  background: rgba(0, 0, 0, 0.8);
  color: white;
  border-radius: 8px;
  font-size: 14px;
}

.point-tip {
  position: absolute;
  top: 20px;
  left: 50%;
  transform: translateX(-50%);
  background: rgba(0, 0, 0, 0.8);
  color: white;
  padding: 8px 16px;
  border-radius: 20px;
  font-size: 14px;
  z-index: 10;
}

.tip-content {
  display: flex;
  align-items: center;
  gap: 8px;
}

.canvas-status {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
  font-size: 12px;
  color: #8c8c8c;
  border-top: 1px solid #f0f0f0;
}

:deep(.el-card__body) {
  padding: 16px;
}

:deep(.el-radio-group) {
  width: 100%;
}

:deep(.el-radio) {
  margin-right: 0;
  margin-bottom: 8px;
  width: 100%;
}
</style>
